package com.neudu.glsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neudu.glsb.mapper.ProductIngredientsMapper;
import com.neudu.glsb.pojo.ProductIngredients;
import com.neudu.glsb.service.ProductIngredientsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductIngredientsServiceImpl extends ServiceImpl<ProductIngredientsMapper, ProductIngredients>
        implements ProductIngredientsService {


    @Override
    public Map<String, Object> loadBasePackageMaterialData(Integer productId) {
        Map<String, Object> result = new HashMap<>();
        // 查询已关联材料
        List<Map<String, Object>> assigned = baseMapper.selectAssignedBasePackageMaterials(productId);
        // 查询可选材料
        List<Map<String, Object>> optional = baseMapper.selectOptionalBasePackageMaterials(productId);
        result.put("assignedMaterials", assigned);
        result.put("optionalMaterials", optional);
        return result;
    }

    @Override
    @Transactional
    public boolean submitBasePackageMaterials(Integer productId, List<ProductIngredients> materials) {
        // 先删除该商品已有的基础原料/包装材料关联
        LambdaQueryWrapper<ProductIngredients> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductIngredients::getProductId, productId)
                .inSql(ProductIngredients::getIngredientId,
                        "SELECT id FROM ingredients WHERE ingredient_type IN ('基础原料', '包装材料')");
        remove(wrapper);

        // 批量插入新关联（含用量）
        if (CollectionUtils.isEmpty(materials)) {
            return true;
        }
        return baseMapper.batchInsertProductMaterials(materials) > 0;
    }

    @Override
    public int removeBasePackageMaterial(Integer productId, Integer ingredientId) {
        LambdaQueryWrapper<ProductIngredients> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductIngredients::getProductId, productId)
                .eq(ProductIngredients::getIngredientId, ingredientId);
        return remove(wrapper) ? 1 : 0;
    }
}